package com.ruoyi.management.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttProducer {

    @Autowired
    private MqttClient mqttClient;

    public Boolean send(String topic, byte[] message) throws Exception {
        Boolean success = false;
        try {
            MqttMessage mqttMessage = new MqttMessage(message);
            mqttMessage.setRetained(true);
            mqttMessage.setQos(1);
            mqttClient.publish(topic, mqttMessage);

            success = true;
        } catch (Exception e) {
            log.error("给EMQX发送消息失败,topic:{},消息:{}", topic, message, e);
        }
        return success;
    }

    public Boolean publish(String topic, MqttMessage message){
        Boolean success = false;
        try {
            mqttClient.publish(topic,message);
            success = true;
        } catch (Exception e) {
            log.error("给EMQX发送消息失败,topic:{},消息:{}", topic, message, e);
        }
        return success;
    }
}